/*
Copyright (C) 2022-2024 Inspur Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/
package impl

import (
	"did-service/common/crypto/gm"
	"did-service/plugins/apicheck/param"
	"reflect"
	"sort"
)

const (
	ApiKeyFieldName    = "ApiKey"
	SignatureFieldName = "Signature"
)

type BaseApiChecker struct {
}

func NewBaseApiChecker() *BaseApiChecker {
	return &BaseApiChecker{}
}

func (checker *BaseApiChecker) ExtractPayload(input interface{}) string {
	t := reflect.TypeOf(input)
	v := reflect.ValueOf(input)
	keys := make([]string, 0)
	for i := 0; i < t.NumField(); i++ {
		fieldName := t.Field(i).Name
		if fieldName != SignatureFieldName {
			keys = append(keys, fieldName)
		}
	}
	sort.Slice(keys, func(i, j int) bool {
		return keys[i] < keys[j]
	})
	payload := ""
	for _, key := range keys {
		payload += v.FieldByName(key).String()
	}

	return payload
}

func (checker *BaseApiChecker) CheckSignature(param *param.ApiCheckParam) bool {
	payload := param.Payload + param.ApiSecret
	signature := param.Signature
	pubKeyHex := param.PubKey

	verify := gm.VerifyWithBase64(pubKeyHex, []byte(payload), signature)
	return verify
}
